package com.nuo.backend.modules.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nuo.backend.common.utils.R;
import com.nuo.backend.modules.security.entity.SecUserTokenEntity;
import com.nuo.backend.modules.shiro.entity.SysUserTokenEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuo.backend.common.utils.PageUtils;
import com.nuo.backend.common.utils.Query;

import com.nuo.backend.modules.security.dao.SecUserTokenDao;
import com.nuo.backend.modules.security.service.SecUserTokenService;


@Service("secUserTokenService")
public class SecUserTokenServiceImpl extends ServiceImpl<SecUserTokenDao, SecUserTokenEntity> implements SecUserTokenService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SecUserTokenEntity> page = this.page(
                new Query<SecUserTokenEntity>().getPage(params),
                new QueryWrapper<SecUserTokenEntity>()
        );

        return new PageUtils(page);

    }

    @Override
    public void saveToken(long userId, String token, Date curDate, Date expireDate) {
        //判断是否生成过token
        SecUserTokenEntity secUserToken = this.getOne(new LambdaQueryWrapper<SecUserTokenEntity>()
                .eq(SecUserTokenEntity::getUserId, userId)
                .eq(SecUserTokenEntity::getIdentity, 0)
        );
        if(secUserToken == null){
            secUserToken = new SecUserTokenEntity();
            secUserToken.setUserId(userId);
            secUserToken.setToken(token);
            secUserToken.setUpdateTime(curDate);
            secUserToken.setExpireTime(expireDate);
            secUserToken.setIdentity(0);
            //保存token
            this.save(secUserToken);

        }else{
            secUserToken.setToken(token);
            secUserToken.setUpdateTime(curDate);
            secUserToken.setExpireTime(expireDate);
            //更新token
            this.update(new LambdaUpdateWrapper<SecUserTokenEntity>()
                    .eq(SecUserTokenEntity::getUserId, userId)
                    .eq(SecUserTokenEntity::getIdentity, 0)
                    .set(SecUserTokenEntity::getToken, token)
                    .set(SecUserTokenEntity::getUpdateTime, curDate)
                    .set(SecUserTokenEntity::getExpireTime, expireDate)
            );
        }
    }

}